<template>
  <el-scrollbar height="100%">
    <div class="w content">
      <video :src="BASE_URL + filmData.filmUrl"
             ref="videoPlayer" @play="handlePlay" @pause="handlePause"
             @timeupdate="handleTimeUpdate"
             style="width:100%;"
             autoplay
             controls>
      </video>
    </div>
    <div class="w info">
        <div style="float: left;width: 150px;">
          <el-image :src="BASE_URL + filmData.poster"
                    style="width: 150px;height: 200px;"
                    alt="Film poster"/>
        </div>
        <div style="float: left;margin-left: 20px;width: 1000px">
          <p>{{ filmData.filmName }} / {{ filmData.englishName }} / {{ tagFormatter(filmData, null, filmData.tag) }} /
            {{ filmData.directorName }} / {{ nationalityFormatter(filmData, null, filmData.region) }} / {{ filmData.duration }}分钟 /
            {{ filmData.releaseDate }} 上映 </p>
          <p style="color: #ebbe56;">电影评分 : {{ filmData.filmRating }}分</p>
          <p style="text-indent: 2em;">{{ filmData.synopsis }}</p>
        </div>

    </div>
    <div class="comments w">
      <component :is="FilmCommentsView" :filmId="filmId" :userId="userId"/>
    </div>

  </el-scrollbar>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import axios from "axios";
import {ElMessage, ElNotification} from "element-plus";
import qs from "qs";
import FilmCommentsView from "@/views/film/comments/FilmCommentsView.vue";

let filmId = new URLSearchParams(window.location.search).get('filmId');
const userId = getUser().id;
const filmData = ref([]);
const search = () => {
  axios.get(BASE_URL + '/v1/film/select?id=' + filmId)
      .then((response) => {
        if (response.data.code === 2000) {
          filmData.value = response.data.data[0];
          console.log(filmData.value);
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  search();
});
const tagList = ref([]);
const nationalityList = ref([]);
onMounted(() => {
  loadDictOptions(tagList, 'tag');
  loadDictOptions(nationalityList, 'nationality');
});
const nationalityFormatter = (row, column, cellValue, index) => {
  if (!nationalityList.value) {
    return cellValue;
  }
  for (let item of nationalityList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tagFormatter = (row, column, cellValue, index) => {
  if (!tagList.value || !cellValue) {
    return cellValue;
  }
  const tagsArray = cellValue.split('/');
  const formattedTags = tagsArray.map(tagValue => {
    for (let item of tagList.value) {
      if (item.value === tagValue) {
        return item.label;
      }
    }
    return tagValue;
  });
  return formattedTags.join('  ');
};
//保存开始数据
const recordVideo = () => {
  let data = qs.stringify({
    userId: getUser().id,
    filmId: filmId,
  });
  axios.post(BASE_URL + '/v1/records/save', data)
      .then(response => {
        if (response.data.code === 2000) {
          console.log('保存观看记录成功')
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })
}
onMounted(() => {
  recordVideo();
});

// 视频播放时间
const videoPlayer = ref(null)
const watchedTime = ref(0)

// 当视频开始播放时调用
const handlePlay = () => {
  console.log('播放')
}

const handlePause = async () => {
  sendWatchedTime()
}
const handleTimeUpdate = () => {
  if (videoPlayer.value) {
    watchedTime.value = videoPlayer.value.currentTime
  }
}
const formatWatchedTime = (totalSeconds) => {
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds - hours * 3600) / 60);
  const seconds = totalSeconds - hours * 3600 - minutes * 60;
  return {hours, minutes, seconds};
};


const watchTime = ref({
  id: '',
  hours: '',
  minutes: '',
  seconds: '',
  userId: '',
  filmId: '',
  time: '',
})
// 发送观看时长到服务器
const sendWatchedTime = () => {
  watchTime.value.hours = formatWatchedTime(watchedTime.value).hours;
  watchTime.value.minutes = formatWatchedTime(watchedTime.value).minutes;
  watchTime.value.seconds = formatWatchedTime(watchedTime.value).seconds;
  watchTime.value.userId = getUser().id;
  watchTime.value.filmId = filmId;
  watchTime.value.time = watchedTime.value;
  let data = qs.stringify(watchTime.value);
  axios.put(BASE_URL + '/v1/records/update', data)
      .then(response => {
        if (response.data.code === 2000) {
          console.log('发送观看时长成功')
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })

}
onUnmounted(() => {
  watchTime.value = {
    id: '',
    hours: '',
    minutes: '',
    seconds: '',
    userId: '',
    filmId: '',
    time: '',
  };
  ElNotification.closeAll();
});

onMounted(() => {
  const timeParam = new URLSearchParams(window.location.search).get('time');
  if (timeParam) {
    const time = parseFloat(timeParam);
    if (!isNaN(time) && videoPlayer.value) {
      videoPlayer.value.currentTime = time;
    }
  }
});



</script>

<style scoped>
.content {
  height: 700px;
}

.comments {
  height: 1000px;
}

.info {
  min-height: 200px;
  overflow: hidden;
  background-color: rgba(15, 24, 39, 0.5);
  box-sizing: border-box;
  border-radius: 10px;
  p {
    color: #FFFFFF;
    line-height: 1.5;
  }
}

.comments {
  height: 1200px;
  margin-top: 10px;
}
</style>